<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @darg-sort="sortTable"
      :detail-params="detailParams"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <!--  -->
        <!-- <el-button v-auth="'add'" type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增种植规格</el-button> -->
        <!-- <el-button v-auth="'batchAdd'" type="primary" :icon="Upload" plain @click="batchAdd">批量添加用户</el-button> -->
        <el-button v-auth="'export'" type="primary" :icon="Download" plain @click="webDerive">导出捐赠记录数据</el-button>
        <!-- <el-button type="primary" plain @click="toDetail">To 子集详情页面</el-button> -->
        <!-- <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected" @click="batchDelete(scope.selectedListIds)">
          批量删除用户
        </el-button> -->
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- nameHeader -->
      <!-- <template #nameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template> -->
      <!-- createTime -->
      <!-- <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template> -->
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <!-- <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button> -->
        <!-- <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button> -->
      </template>
    </ProTable>
    <recordDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="捐赠记录">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { Tree } from "@/api/interface";
// import { useDownload } from "@/hooks/useDownload";
// import { useAuthButtons } from "@/hooks/useAuthButtons";
import { View } from "@element-plus/icons-vue";

import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/record.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import recordDrawer from "@/views/proTable/components/recordDrawer.vue";
// HeaderRenderScope
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
// Refresh，Upload
import { Download } from "@element-plus/icons-vue";
import { getSpecList } from "@/api/modules/record";
import { pay_status, type } from "@/utils/dict";
import { exportExcel } from "@/utils/ExportExcel";

const router = useRouter();

// 跳转详情页
// const toDetail = () => {
//   router.push(`/proTable/useProTable/detail/${Math.random().toFixed(3)}?params=detail-page`);
// };

onMounted(() => {
  // const id = router.currentRoute.value.query.id;
  // if (id && id !== "undefined") {
  //   console.log(id, "id");
  // } else {
  // }
});

// const pickerOptions = {
//   shortcuts: [
//     {
//       text: "今天",
//       onClick(picker) {
//         const end = new Date();
//         const start = new Date();
//         start.setHours(0, 0, 0, 0); // 设置时间为0点0分0秒0毫秒
//         picker.$emit("pick", [start, end]);
//       }
//     },
//     {
//       text: "最近两天",
//       onClick(picker) {
//         const end = new Date();
//         const start = new Date();
//         start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
//         picker.$emit("pick", [start, end]);
//       }
//     },
//     {
//       text: "最近三天",
//       onClick(picker) {
//         const end = new Date();
//         const start = new Date();
//         start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
//         start.setHours(0, 0, 0, 0); // 设置时间为0点0分0秒0毫秒
//         picker.$emit("pick", [start, end]);
//       }
//     },
//     {
//       text: "最近一周",
//       onClick(picker) {
//         const end = new Date();
//         const start = new Date();
//         start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
//         start.setHours(0, 0, 0, 0); // 设置时间为0点0分0秒0毫秒
//         picker.$emit("pick", [start, end]);
//       }
//     },
//     {
//       text: "最近一个月",
//       onClick(picker) {
//         const end = new Date();
//         const start = new Date();
//         start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
//         picker.$emit("pick", [start, end]);
//       }
//     },
//     {
//       text: "最近三个月",
//       onClick(picker) {
//         const end = new Date();
//         const start = new Date();
//         start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
//         picker.$emit("pick", [start, end]);
//       }
//     }
//   ]
// };

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ planting_tree_id: Number(router.currentRoute.value.query.id) });
// 索引
const pageIndex = reactive({
  page: 1,
  pageSize: 10
});
// 详情页参数
const detailParams = reactive({ id: Number(router.currentRoute.value.query.id) });
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && page && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  console.log(data, "data");
  pageIndex.page = data.current_page;
  pageIndex.pageSize = data.per_page;
  return {
    list: data.data,
    total: data.total,
    page: data.current_page,
    pageSize: data.per_page
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getSpecList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  // newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  // newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  // delete newParams.createTime;
  params.page || (newParams.page = 1);
  params.pageSize || (newParams.pageSize = 10);
  console.log(params, "params");
  return getSpecList(newParams);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
// const { BUTTONS } = useAuthButtons();

// 自定义渲染表头（使用tsx语法）
// const headerRender = (scope: HeaderRenderScope<Tree.ResAreaList>) => {
//   return (
//     <el-button type="primary" onClick={() => ElMessage.success("我是通过 tsx 语法渲染的表头")}>
//       {scope.column.label}
//     </el-button>
//   );
// };

// 表格配置项
const columns = reactive<ColumnProps<Tree.ResTreeList>[]>([
  // { type: "selection", fixed: "left", width: 70 },
  // { type: "sort", label: "排序", width: 80 },
  // {
  //   type: "index",
  //   label: "索引",
  //   width: 85
  // }, //
  {
    // type: "index",
    prop: "index",
    label: "索引",
    width: 85,
    render(scope) {
      return <div>{(pageIndex.page - 1) * pageIndex.pageSize + scope.$index + 1}</div>;
    }
  }, //
  { type: "expand", label: "展开", width: 70 }, //
  // {
  //   prop: "name",
  //   label: "序号",
  //   width: 96
  // },
  {
    prop: "name",
    label: "捐赠主体名称",
    search: { el: "input" },
    width: 116
  },
  {
    prop: "contact_information",
    label: "捐赠主体联系方式",
    search: { el: "input" },
    width: 148
  },
  {
    prop: "out_trade_no",
    label: "商户订单号",
    search: { el: "input" },
    width: 160
  },
  {
    prop: "prepay_id",
    label: "微信预付单号",
    search: { el: "input" },
    width: 150
  },
  {
    prop: "pay_status",
    label: "付款状态",
    tag: true,
    enum: pay_status,
    search: { el: "tree-select" },
    fieldNames: { label: "label", value: "value" },
    width: 104
  },
  {
    prop: "planting_area_name",
    label: "种植区域名称",
    search: { el: "input" },
    width: 160
  },
  {
    prop: "planting_tree_name",
    label: "种植树种名称",
    search: { el: "input" },
    width: 160
  },
  {
    prop: "planting_tree_specification_name",
    label: "种植树种规格名称",
    search: { el: "input" },
    width: 150
  },
  {
    prop: "type",
    label: "捐赠主体类型",
    tag: true,
    sortable: true, // 排序
    enum: type,
    search: { el: "tree-select" },
    fieldNames: { label: "label", value: "value" },
    width: 140
    // render(scope) {
    //   return (
    //     <div>
    //       <el-tag type={scope.row.type == 2 ? "primary" : scope.row.type == 1 ? "success" : "info"}>
    //         {scope.row.type == 2 ? "公司/组织" : scope.row.type == 1 ? "个人" : "未知"}
    //       </el-tag>
    //     </div>
    //   );
    // }
  },
  {
    prop: "donate_amount",
    label: "捐赠金额",
    search: { el: "input" },
    sortable: true,
    width: 110
  },
  {
    prop: "donate_number",
    label: "捐赠数量",
    search: { el: "input" },
    sortable: true,
    width: 110
  },
  {
    prop: "donate_total",
    label: "捐赠总额",
    search: { el: "input" },
    sortable: true,
    width: 110
  },
  {
    prop: "pay_at",
    label: "付款时间",
    // headerRender,
    width: 140,
    search: {
      el: "date-picker",
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" }
      // defaultValue: ["2022-11-12 11:35:00", "2022-12-12 11:35:00"]
      // defaultValue: [null]
    },
    sortable: true // 排序
  },
  {
    prop: "donate_at",
    label: "捐赠时间",
    // headerRender,
    width: 140,
    search: {
      el: "date-picker",
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" }
      // defaultValue: ["2022-11-12 11:35:00", "2022-12-12 11:35:00"]
      // defaultValue: [null]
    },
    sortable: true // 排序
  },
  {
    prop: "created_at",
    label: "创建时间",
    // headerRender,
    width: 140,
    search: {
      el: "date-picker",
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" }
      // defaultValue: ["2022-11-12 11:35:00", "2022-12-12 11:35:00"]
      // defaultValue: [null]
    },
    sortable: true // 排序
  },
  {
    prop: "updated_at",
    label: "更新时间",
    // headerRender,
    width: 140,
    search: {
      el: "date-picker",
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" }
      // defaultValue: ["2022-11-12 11:35:00", "2022-12-12 11:35:00"]
      // defaultValue: [null]
    },
    sortable: true // 排序
  },
  {
    prop: "openid_mp",
    label: "openid",
    search: { el: "input" },
    sortable: true, // 排序，
    width: 110
  },
  { prop: "operation", label: "操作", fixed: "right", width: 100 }
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};

// 格到本地xlsx文件 ----
const webDerive = () => {
  ElMessageBox.confirm("是否确认导出当前页面数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    //deleteDate  选中数据列表
    // let titleArr = ["序号", "规格名称", "归属树种", "认捐金额", "备注", "创建时间", "更新时间", "状态"];
    const titleArr = [
      "序号",
      "捐赠主体名称",
      "捐赠主体联系方式",
      "商户订单号",
      "微信预付单号",
      "付款状态",
      "捐赠单价",
      "捐赠数量",
      "捐赠总额",
      "种植区域名称",
      "种植树种名称",
      "种植树种规格名称",
      "捐赠主体类型",
      "付款时间",
      "捐赠时间",
      "创建时间",
      "更新时间",
      "openid"
    ];
    const oldTableData = JSON.parse(JSON.stringify(proTable.value?.tableData));
    // const filterVal = ["index", "name", "planting_tree_name", "donate_amount", "memo", "created_at", "updated_at", "status"];
    const filterVal = [
      "index",
      "name",
      "contact_information",
      "out_trade_no",
      "prepay_id",
      "pay_status",
      "donate_amount",
      "donate_number",
      "donate_total",
      "planting_area_name",
      "planting_tree_name",
      "planting_tree_specification_name",
      "type",
      "pay_at",
      "donate_at",
      "created_at",
      "updated_at",
      "openid_mp"
    ];
    // const newTableData = oldTableData.map((v, i) =>
    //   filterVal.map(j => {
    //     if (j === "index") {
    //       return i;
    //     } else if (j === "status") {
    //       return v[j] === 0 ? "禁用" : "正常";
    //     } else {
    //       return v[j];
    //     }
    //   })
    // );
    const newTableData = oldTableData.map((v, i) =>
      filterVal.map(j => {
        if (j === "index") {
          return i;
        } else if (j === "pay_status") {
          return v[j] === 0 ? "未付款" : "已付款";
        } else if (j === "type") {
          return v[j] === 0 ? "未知" : v[j] === 1 ? "个人" : "公司/组织";
        } else {
          return v[j];
        }
      })
    );
    const item = oldTableData[0];
    console.log(newTableData, "newTableData");
    const title = `${item.name} - ${new Date().toLocaleString().replaceAll("/", "-")}`;
    exportExcel({
      json: newTableData, //数据
      name: title, //表名
      titleArr: titleArr, //表头
      sheetName: "sheet" //页签
    });
  });
};

// interface excelType {
//   json: object;
//   name: string;
//   titleArr: string[];
//   sheetName: string;
// }

// 批量添加用户
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
// const batchAdd = () => {
//   const params = {
//     title: "用户",
//     tempApi: exportUserInfo,
//     importApi: BatchAddUser,
//     getTableList: proTable.value?.getTableList
//   };
//   dialogRef.value?.acceptParams(params);
// };

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof recordDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Tree.ResRecordList> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    // api: title === "新增" ? addMenu : title === "编辑" ? editMenu : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
@/utils/ExportExcel
